/*
 * Copyright (C) 2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.Diagnostics;
using System.Threading;

using Gtk;
using Mono.GetOptions;
using Mono.Unix;

using DCSharp.Logging;

namespace DCSharp.Gui
{
	public static class DCSharpEntry
	{
		[STAThread]
		public static void Main(string[] args)
		{
			Thread.CurrentThread.Name = "Main";
			if (!GLib.Thread.Supported)
			{
				GLib.Thread.Init();
			}

			Application.Init("dcsharp", ref args);

			Controller controller = new Controller();

			// Parse the arguments
			Options options = new Options();
			options.ProcessArgs(args);

#if ENABLE_DBUS
			// Initialize D-Bus
			NDesk.DBus.BusG.Init();

			// Check for an existing instance
			IApplication instance = Controller.FindInstance();
			if (instance != null)
			{
				instance.Present();
				foreach (string arg in options.RemainingArguments)
				{
					instance.ConnectTo(arg);
				}

				Gdk.Global.NotifyStartupComplete();
				System.Environment.Exit(0);
			}

			// Register the controller
			controller.RegisterService();
#endif
			// Localization
			string localeDir = Environment.GetEnvironmentVariable("DCSHARP_LOCALE");
			if (localeDir == null)
			{
				localeDir = "./locale";
			}
			Catalog.Init("dcsharp", localeDir);

			// Logging
			LogManager.Handlers += LogManager.DefaultHandler;
#if DEBUG
			Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
			Debug.AutoFlush = true;
#endif
			// Initialize
			Globals.Init();
			controller.HandleArgs(options.RemainingArguments);

			// Run!
			try
			{
				Application.Run();
			}
			catch (Exception e)
			{
				Console.Error.WriteLine("Unhandled exception: {0}", e);
			}
			finally
			{
				Globals.Shutdown();
#if ENABLE_DBUS
				controller.UnregisterService();
#endif
			}
		}
	}
}
